nfs = require("@native.fs");
sys = require("@native.builtin");

function size(path){
    var fd = nfs.open(path, "rb");
    if(fd < 0)
        return undefined;
    var size = nfs.size(fd);
    nfs.close(fd);
    return size;
}

function exists(path){
    if(nfs.exists(path) >=0 )
        return true;
    else 
        return false;
}

function rename(oldpath, newpath){
    if(nfs.rename(oldpath, newpath) >=0)
        return true;
    else 
        return false;
}

function remove(oldpath){
    if(nfs.remove(oldpath) >=0)
        return true;
    else 
        return false;
}

function readFile(path, mode){
    var fd = nfs.open(path, mode);
    if(fd < 0)
        return undefined;
    var size = nfs.size(fd);
    if(size == 0)
        return "";   
    var cp_buff = sys.malloc(size);
    if(cp_buff == null){
        nfs.close(fd);
        return undefined;
    }
    var res = nfs.read(fd, cp_buff, size);
    nfs.close(fd);
    var buffer = sys.toJsString(cp_buff, size);
    sys.free(cp_buff);
    return buffer;
}


function writeFile(path, buf, mode){
    var fd = nfs.open(path, mode);
    if(fd < 0)
        return undefined;
    var cp_buff = sys.getaddr(buf);
    var size = sys.getlen(buf);
    var res = nfs.write(fd, cp_buff, size);
    nfs.close(fd);

    if (res >= 0) return true;
    else return false;
}